package cmu.mobile.lab;

//import java.io.InputStream;

import java.io.File;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class Dashboard extends Activity {
	// comment
	/** Called when the activity is first created. */

	private static final int GET_USER_INFO = 3;
	private static final String GET_PICTURE_CODE = "savedPictureDash";
	private static final String GET_NAME_CODE = "savedNameDash";
	String userDisplayName="Set Name";
	String imagePath;
	TextView nameText;
	SharedPreferences dashboard;
	String picturePath;
	ImageView profilePicture;
	Database mDbHelper;
	SharedPreferences prefs;
	private BroadcastReceiver idReceiver;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_dashboard);
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        
      //mDbHelper = new Database(Dashboard.this);
   
    	//Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_URI, "owner");
    	
    	//	Cursor c = managedQuery(uri, null, null, null, null);
    	//	int nameColumn = c.getColumnIndex(People.NAME);
    	//	CharSequence name = (CharSequence) c.getString(nameColumn);
    	//	theName.setText(name);
        
//        String url = "content://mms/";
//        getContentResolver().registerContentObserver(Uri.parse(url), true, 
//        		new MMSObserver(new Handler(), getContentResolver()));
    	
        nameText = (TextView) findViewById(R.id.name_entry);
        profilePicture = ((ImageView)findViewById(R.id.profile_pic));
        Button runAddItem = (Button)findViewById(R.id.addItemsBtn);
        
        
        prefs = PreferenceManager.getDefaultSharedPreferences(Dashboard.this);
		imagePath = prefs.getString(GET_PICTURE_CODE, imagePath);
		userDisplayName = prefs.getString(GET_NAME_CODE, userDisplayName);
		
		if (imagePath != null)
		{
			Uri u = Uri.parse("content://media" + imagePath);
			profilePicture.setImageURI(u);
		}
		if (userDisplayName != null)
		{
			nameText.setText(userDisplayName);
		}
        
        
        runAddItem.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				// action to perform on click
				Intent intent = new Intent(Dashboard.this, AddItem.class);
				intent.putExtra("ownerid", prefs.getString(EditInfo
						.GET_NUMBER_CODE, null));
				startActivity(intent);
				//mDbHelper.open();
				//mDbHelper.addData();
				//mDbHelper.close();
			
			}
		});
     
        Button runMyItems = (Button)findViewById(R.id.myItemsBtn);
        runMyItems.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				// action to perform on click
				Intent myItemsIntent = new Intent(Dashboard.this, MyFashionProfile.class);
				startActivity(myItemsIntent);
				
			}
		});
        
        Button runFriends = (Button)findViewById(R.id.friendsBtn);
        runFriends.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				// action to perform on click
				Intent friendsIntent = new Intent(Dashboard.this, FriendsList.class);
				startActivity(friendsIntent);
				
				
				
			}
		});
        
     // fashion profile button
		findViewById(R.id.myItemsBtn).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent myProfileIntent = new Intent(Dashboard.this, MyFashionProfile.class);
				//myProfileIntent.putExtra("username", userDisplayName);
				//myProfileIntent.putExtra("image", imagePath);
				startActivity(myProfileIntent);
			}
		});
        
        Button runEdit = (Button)findViewById(R.id.edit);
        runEdit.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				// action to perform on click
				// TODO: pass on image path (?) and name
				Intent editIntent = new Intent(Dashboard.this, EditInfo.class);
				editIntent.putExtra("username", userDisplayName);
				startActivityForResult(editIntent,GET_USER_INFO);
				//startActivity(editIntent);
				
			}
		});
        
        //InputStream inputstream = openPhoto(1);
        //setImageURI(ContactsContract.Contacts.Photo.this);
        
        idReceiver = new BroadcastReceiver() {
			
        	@Override
			public void onReceive(Context context, Intent intent) {
        		String id = intent.getStringExtra("itemid");
        		MMSContent newItem = ImageLoader.downloadItem(id);
        		Database database = new Database(Dashboard.this);
        		database.open();
        		database.addItem(newItem);
        		database.close();
        		
//        		// ---testing stuff below---
//        		nameText.setText(newItem.getMessageText());
//        		profilePicture.setImageURI(Uri.fromFile(new File(
//        				newItem.getImagePath())));
//        		// ---testing stuff above---
        	}
        };
        registerReceiver(idReceiver, new IntentFilter(SMSReceiver
        		.FASHIONISTA_UPDATE));
        
    }

	// OnActivityResult event handler (needed to handle the results returned by
	// sub-Activities
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
			case (GET_USER_INFO): {
				if (resultCode == Activity.RESULT_OK) {
					userDisplayName = data.getExtras().getString("username");
					if(userDisplayName != null)
					{
						nameText.setText(userDisplayName);
					}
					imagePath = data.getExtras().getString("image");
					if(imagePath != null)
					{
						Uri u = Uri.parse("content://media" + imagePath);
						profilePicture.setImageURI(u);
					}
					
					prefs = PreferenceManager.getDefaultSharedPreferences(Dashboard.this);
	        		SharedPreferences.Editor speDash = prefs.edit();
	        		speDash.putString(GET_PICTURE_CODE, imagePath);
	        		speDash.putString(GET_NAME_CODE, userDisplayName);
	        		speDash.commit();
	        		
				}
				break;
			}
		}
	}
	
}
    
/*
    public InputStream openPhoto(long contactId) {
        Uri contactUri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, contactId);
        Uri photoUri = Uri.withAppendedPath(contactUri, ContactsContract.Contacts.Photo.CONTENT_DIRECTORY);
        Cursor cursor = getContentResolver().query(photoUri,
             new String[] {ContactsContract.Contacts.Photo.IS_PRIMARY}, null, null, null);
        if (cursor == null) {
            return null;
        }
        try {
            if (cursor.moveToFirst()) {
                byte[] data = cursor.getBlob(0);
                if (data != null) {
                    return new ByteArrayInputStream(data);
                }
            }
        } finally {
            cursor.close();
        }
        return null;
    }*/
	

